// pages/category/index.js
import { api } from '../../request/index'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 左侧
    leftDataList: [],
    // 右侧
    rightDataList: [],
    // 选中左侧菜单
    currentIndex: 0,
    // 右侧滚动条距离顶部距离
    scrollTop: 0,
  },
  cates: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    /**
     * 1.看本地是否有数据
     *  有就不用取,没有发请求
     * 2.有旧数据,先判断时间有没有过期
     */
    const Cates = wx.getStorageSync('cates')
    if (!Cates) {
      this.getList()
    } else {
      // 判断时间有没有超时,
      let pastdue_time = 1000 * 10
      if (Date.now() - Cates.time > pastdue_time) {
        this.getList()
      } else {
        // 未超时
        this.cates = Cates.data
        let leftDataList = this.cates.map((v) => v.cat_name)
        let rightDataList = this.cates[0].children
        this.setData({
          leftDataList,
          rightDataList,
        })
      }
    }
  },

  // 获取数据
  async getList() {
    let res = await api({
      url: '/categories',
    })
    this.cates = res.message
    // 拿到数据本地缓存
    wx.setStorageSync('cates', { time: Date.now(), data: this.cates })
    // 处理数据赋值给左边菜单和右边内容
    let leftDataList = this.cates.map((v) => v.cat_name)
    let rightDataList = this.cates[0].children
    this.setData({
      leftDataList,
      rightDataList,
    })
  },
  // 侧边菜单点击
  handleClick(e) {
    let { index } = e.currentTarget.dataset
    let rightDataList = this.cates[index].children
    this.setData({
      currentIndex: index,
      rightDataList,
      scrollTop: 0,
    })
  },
})
